package com.heima.search.controller;

import cn.hutool.core.util.StrUtil;
import com.heima.common.util.LoginUserInfo;
import com.heima.common.util.UserInfoThreadLocal;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.HistorySearchDto;
import com.heima.model.search.dto.UserSearchDto;
import com.heima.model.search.pojo.SearchHistory;
import com.heima.search.service.ApArticleSearchService;
import com.heima.search.service.SearchHistoryService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1")
public class ArticleSearchController {

    @Resource
    private ApArticleSearchService apArticleSearchService;

    @Resource
    private SearchHistoryService searchHistoryService;

    /**
     * APP端文章搜索功能
     * @param dto 搜索参数
     * @return 搜索结果
     */
    @PostMapping("/article/search/search")
    public ResponseResult search(@RequestBody UserSearchDto dto) throws IOException {
        LoginUserInfo user = UserInfoThreadLocal.get();
        Long userId = (user != null) ? user.getId() : null;

        // 保存搜索历史
        if (userId != null && dto.getSearchWords() != null) {
            searchHistoryService.insert(dto.getSearchWords(), userId);
        }

        List<Map<String, Object>> resList = apArticleSearchService.search(dto);
        return ResponseResult.success(resList);
    }

    /**
     * 搜索建议
     * @param userSearchDto 搜索建议参数
     * @return 搜索建议结果
     */
    @PostMapping("/associate/search")
    public ResponseResult suggestion(@RequestBody UserSearchDto userSearchDto) throws IOException {
        //1、空过滤
        if (StrUtil.isEmpty(userSearchDto.getSearchWords())){
            return ResponseResult.success(Collections.emptyList());
        }

        //2、自动补全搜索
        List<String> suggestionList = apArticleSearchService.searchSuggestion(userSearchDto.getSearchWords());

        //3、构建List<Map>对象
        // List<Map<String, String>> dataList = suggestionList.stream().map(s -> {
        //     Map<String, String> acMap = new HashMap<>();
        //     acMap.put("id", UUID.randomUUID().toString());
        //     acMap.put("associateWords", s);
        //     return acMap;
        // }).collect(Collectors.toList());
        return ResponseResult.success(suggestionList);
    }

    /**
     * 加载搜索历史
     * @return 搜索历史列表
     */
    @PostMapping("/history/load")
    public ResponseResult<List<SearchHistory>> loadHistory() {
        LoginUserInfo user = UserInfoThreadLocal.get();
        if (user == null) {
            return ResponseResult.error(AppHttpCodeEnum.NEED_LOGIN);
        }
        List<SearchHistory> historyList = searchHistoryService.findUserSearchHistory(user.getId());
        return ResponseResult.success(historyList);
    }

    /**
     * 删除搜索历史
     * @param dto 包含历史记录ID的DTO
     * @return 删除结果
     */
    @PostMapping("/history/del")
    public ResponseResult<?> deleteHistory(@RequestBody HistorySearchDto dto) {
        LoginUserInfo user = UserInfoThreadLocal.get();
        if (user == null) {
            return ResponseResult.error(AppHttpCodeEnum.NEED_LOGIN);
        }
        searchHistoryService.deleteUserSearchHistory(user.getId(), dto);
        return ResponseResult.success();
    }

    /***
     * 数据批量导入
     */
    @GetMapping(value = "/init")
    public String initData() throws IOException {
        apArticleSearchService.importData();
        return "SUCCESS";
    }
}
